/*
 *   Copyright 1999-2018 dragonshard.net.
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package net.dragonshard.dsf.dynamic.datasource.provider;

import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import net.dragonshard.dsf.dynamic.datasource.DynamicDataSourceCreator;
import net.dragonshard.dsf.dynamic.datasource.configuration.DataSourceProperty;
import net.dragonshard.dsf.dynamic.datasource.configuration.DynamicDataSourceProperties;

/**
 * YML数据源提供者
 *
 * @author TaoYu Kanyuxia
 * @since 1.0.0
 */
@Slf4j
public class YmlDynamicDataSourceProvider implements DynamicDataSourceProvider {

  /**
   * 多数据源参数
   */
  private DynamicDataSourceProperties properties;
  /**
   * 多数据源创建器
   */
  private DynamicDataSourceCreator dynamicDataSourceCreator;

  public YmlDynamicDataSourceProvider(DynamicDataSourceProperties properties,
    DynamicDataSourceCreator dynamicDataSourceCreator) {
    this.properties = properties;
    this.dynamicDataSourceCreator = dynamicDataSourceCreator;
  }

  @Override
  public Map<String, DataSource> loadDataSources() {
    Map<String, DataSourceProperty> dataSourcePropertiesMap = properties.getDatasource();
    Map<String, DataSource> dataSourceMap = new HashMap<>(dataSourcePropertiesMap.size());
    for (Map.Entry<String, DataSourceProperty> item : dataSourcePropertiesMap.entrySet()) {
      String pollName = item.getKey();
      DataSourceProperty dataSourceProperty = item.getValue();
      dataSourceProperty.setPollName(pollName);
      dataSourceMap.put(pollName, dynamicDataSourceCreator.createDataSource(dataSourceProperty));
    }
    return dataSourceMap;
  }
}
